package com.notary.tx_live_plugin.platform;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.view.View;

import com.notary.tx_live_plugin.util.TxLogger;
import com.notary.tx_live_plugin.util.TxConstant;
import com.notary.tx_live_plugin.util.PushManager;
import com.notary.tx_live_plugin.widget.TxLivePushView;

import java.lang.ref.WeakReference;
import java.util.HashMap;

import io.flutter.plugin.common.BinaryMessenger;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.platform.PlatformView;

/**
 * 直播录制的platform view，原生提供给flutter的widget控件
 */
public class TxLivePushPlatformView implements PlatformView {

    private final PushManager pushManager;
    private MethodChannel channel;
    private TxLivePushView txLivePushView;
    private final WeakReference<Context> mContextWeak;
    private final HashMap<String, Object> params;

    public TxLivePushPlatformView(BinaryMessenger binaryMessenger, Context context, int viewId, HashMap<String, Object> params) {
        this.mContextWeak = new WeakReference<>(context);
        this.params = params;
        //设置channel
        pushManager = PushManager.getInstance();
        PushMethodCallHandlerImpl callHandler = new PushMethodCallHandlerImpl(pushManager);
        final String channelName = TxConstant.Channel.PUSH_PREFIX + viewId;
        channel = new MethodChannel(binaryMessenger, channelName);
        channel.setMethodCallHandler(callHandler);
        final Handler handler = new Handler(Looper.getMainLooper());
        pushManager.setOnPushCallback((String methodName, Object data) ->{
            //invokeMethod @UiThread要求主线程运行，推流回调可能在子线程
            handler.post(()->{
                if(channel != null){
                    channel.invokeMethod(methodName,data);
                }
            });
        });
    }

    @Override
    public View getView() {
        if(txLivePushView == null) {
            txLivePushView =  new TxLivePushView(mContextWeak.get());
            txLivePushView.setParams(params);
            pushManager.setPushView(txLivePushView);
            pushManager.requestPermissionForPush();
        }
        return txLivePushView;
    }

    @Override
    public void dispose() {
        if(txLivePushView != null) txLivePushView.onDestroy();
        txLivePushView = null;
        pushManager.clear();
//        channel.setMethodCallHandler(null);
//        channel = null;
    }
}
